﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SmartSpace.Core;

namespace SsTool.Base.Windows
{
    /// <summary>
    /// Interaction logic for AssignUserToRoleWindow.xaml
    /// </summary>
    public partial class AssignUserToRoleWindow : Window
    {
        public AssignUserToRoleWindow(Role role)
        {
            InitializeComponent();
            this.DataContext = role;

            this.Loaded += new RoutedEventHandler(AssignUserToRoleWindow_Loaded);
        }

        void AssignUserToRoleWindow_Loaded(object sender, RoutedEventArgs e)
        {
            LoadContains();
            LoadUsers();
        }

        private void LoadContains()
        {
            ICoreService service = App.Get<ICoreService>();
            this._ctlGridContainsUser.ItemsSource = service.GetContainsUsers(this.DataContext as Role);
        }

        private void LoadUsers()
        {
            ICoreService service = App.Get<ICoreService>();
            _ctlGridUser.ItemsSource = service.GetUsers(0, 999);
        }

        private void _ctlBtnAssign_Click(object sender, RoutedEventArgs e)
        {
            if (this._ctlGridUser.SelectedItems != null
                && this._ctlGridUser.SelectedItems.Count > 0)
            {
                for (int index = 0; index < this._ctlGridUser.SelectedItems.Count; index++)
                {
                    User selectedUser = _ctlGridUser.SelectedItems[index] as User;
                    if (selectedUser != null)
                    {
                        ICoreService service = App.Get<ICoreService>();

                        service.AssignUser(this.DataContext as Role, selectedUser, selectedUser);
                    }
                    LoadContains();
                }
            }
        }

        private void _ctlBtnRemove_Click(object sender, RoutedEventArgs e)
        {
            User selectedUser = this._ctlGridContainsUser.SelectedItem as User;
            if (selectedUser != null)
            {
                ICoreService service = App.Get<ICoreService>();

                service.RemoveUser(this.DataContext as Role, selectedUser);
                LoadContains();
            }
        }

        private void _ctlBtnClose_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }
    }
}
